import { type TableColumnType } from 'ant-design-vue';
import { reactive, shallowReadonly, toRefs, type ToRefs } from 'vue';
import type { RouteLocationRaw } from 'vue-router';

/**
 * ErrorMsgModal 组件联合使用
 * 增加确定按钮和回调事件
 */

export interface ErrorMsgData {
  title?: string;
  msg: string;
  link?: RouteLocationRaw | undefined;
  table?: { columns: TableColumnType[]; dataSource: string[][] };
  code?: number | undefined;
  solution?: string;
}

export interface ErrorMsg extends ErrorMsgData {
  visible: boolean;
  resolve?: (value?: unknown) => void;
}

const errMsg = reactive<ErrorMsg>({
  visible: false,
  title: '操作错误',
  msg: '',
  link: undefined,
  table: { columns: [], dataSource: [] },
  code: 0,
  solution: '',
  resolve: undefined,
});
// 关闭弹框的定时器
let timer: any;
// 导出参数
export const errProps: ToRefs<Readonly<ErrorMsg>> = toRefs(shallowReadonly(errMsg));

// 关闭错误提示弹框
export function hideMsgModal() {
  errMsg.visible = false;
  errMsg.resolve && errMsg.resolve();
  timer && clearTimeout(timer);
}

/**
 * 显示错误提示弹框
 * @param {any} errRes
 * @param {number} duration
 * @returns void
 */

export function showErrorMsg(errRes: ErrorMsgData, duration = 5) {
  hideMsgModal();
  // 如果是符合展示条件的错误信息使用Modal
  const { table, solution, link, code, msg, title = '操作失败' } = errRes;
  if ((table && table.dataSource && table.dataSource.length > 0) || solution) {
    return new Promise(resolve => {
      errMsg.visible = true;
      errMsg.title = title;
      errMsg.link = link;
      errMsg.table = table;
      errMsg.code = code;
      errMsg.msg = msg;
      errMsg.solution = solution;
      errMsg.resolve = resolve;
      timer = setTimeout(hideMsgModal, duration * 1000);
    });
  } else {
    return Promise.resolve();
  }
}
